package com.liao.controller;

import com.github.pagehelper.PageHelper;
import com.liao.bean.Role;
import com.liao.bean.result.Code;
import com.liao.bean.result.Msg;
import com.liao.bean.result.PageResult;
import com.liao.bean.result.Result;
import com.liao.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @ResponseBody
    @RequestMapping("/queryRoleListByPage")
    public PageResult<Role> queryRoleListByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                                @RequestParam(defaultValue = "5") Integer pageSize,
                                                @RequestParam(defaultValue = "") String roleName) throws Exception {
        PageResult<Role> rolePageResult = roleService.queryRoleListByPage(currentPage,pageSize,roleName);

        return rolePageResult;
    }

    @ResponseBody
    @RequestMapping("/addRole")
    public Result addRole(@RequestBody Role role) throws Exception {
        Role role1=roleService.queryRoleById(role.getRoleId());
        if(null!=role1){
            return new Result(false, Code.ROLE_ADD_FAIL, Msg.ROLE_ADD_FAIL);
        }else {
            roleService.addRole(role);
            return new Result(true, Code.ROLE_ADD_SUCCESS, Msg.ROLE_ADD_SUCCESS);
        }

    }

    @ResponseBody
    @RequestMapping("/deleteRole")
    public Result deleteRole(String roleId) throws Exception {
        roleService.deleteRole(roleId);
        return new Result(true,Code.ROLE_DELETE_SUCCESS, Msg.ROLE_DELETE_SUCCESS);
    }

    @ResponseBody
    @RequestMapping("/deleteRoleIds")
    public Result deleteRoleIds(@RequestParam("roleIds[]") List<String> roleIds) throws Exception {
        for (String roleId : roleIds) {
            try {
                roleService.deleteRole(roleId);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,Code.ROLE_DELETE_FAIL, Msg.ROLE_DELETE_FAIL);
            }

        }
       return new Result(true,Code.ROLE_DELETE_SUCCESS, Msg.ROLE_DELETE_SUCCESS);
    }

    @ResponseBody
    @RequestMapping("/editRole")
    public Result editRole(String oldRoleId,String roleId,String roleName,String roleDesc) throws Exception {
        roleService.editRole(oldRoleId,roleId,roleName,roleDesc);
        return new Result(true,Code.ROLE_EDIT_SUCCESS, Msg.ROLE_EDIT_SUCCESS);
    }
}
